package com.ruoyi.mobile.api;

import com.ruoyi.common.core.domain.AjaxResults;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.WeChatHttpUtils;
import com.ruoyi.common.utils.WeChatUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.qsng.domain.*;
import com.ruoyi.qsng.service.*;
import com.ruoyi.qsng.service.impl.KUsersServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信支付控制器
 *
 * @author rz
 * @date 2023-06-19
 */
@Api(tags = "微信支付控制器")
@RestController
@RequestMapping
@Slf4j
public class WechatPayController {



    @Autowired
    private IKUsersService kUsersService;

    @Autowired
    private IKCoursePurchaseService kCoursePurchaseService;

    @Autowired
    private IKCourseService kCourseService;

    @Autowired
    private IKIntegralOrderService kIntegralOrderService;

    @Autowired
    private IKIntegralDetailedService kIntegralDetailedService;

    @ApiOperation(value = "支付")
    @ResponseBody
    @RequestMapping(value = "/wechatPay/pay",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    public Map<String,String> weChatPay(HttpServletRequest request, String orderId) {
        KCoursePurchase kCoursePurchase =kCoursePurchaseService.selectKCoursePurchaseById(orderId);
        KCourse  kCourse=kCourseService.selectKCourseById(kCoursePurchase.getCourseId());
        if(kCourse.getTotalQuota()-kCourse.getSold()<=0){
            Assert.notNull(null, "课程数量不足，无法购买！");
        }
        String ip = IpUtils.getIpAddr(request);
        String[] ipArr = ip.split(",");
        //调用微信统一下单接口
        Map<String, String> map = new HashMap<>();
        //公众账号ID
        map.put("appid", WeChatUtils.weChatAppid);
        //商户号
        map.put("mch_id", WeChatUtils.weChatPayMchId);
        //随机字符串
        map.put("nonce_str", WeChatUtils.generateNonceStr());
        //商品描述
        map.put("body", "课程"+kCoursePurchase.getCourseId());
        //商户订单号
        String  outTradeNoWx=WeChatUtils.generateNonceStr();
        map.put("out_trade_no", outTradeNoWx);
        //标价金额
        map.put("total_fee", kCoursePurchase.getPrice().multiply(BigDecimal.valueOf(100)).intValue()+"");
        //交易类型
        map.put("trade_type", "JSAPI");
        //终端IP
        map.put("spbill_create_ip", ipArr[0]);
        //通知地址
        map.put("notify_url", WeChatUtils.weChatPayNotifyUrl);

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户id失败！");
        KUsers kUsers=kUsersService.selectKUsersById(String.valueOf(userId));
        //openid 如何获取查询微信支付官方文档
        map.put("openid", kUsers.getOpenId());
        //签名类型
        map.put("sign_type", "MD5");
        //签名
        try {
            map.put("sign", WeChatUtils.generateSignature(map, WeChatUtils.weChatPayKey, "MD5"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String resultXml = null;
        Map<String, String> resultMap = null;
        try {
            resultXml = WeChatHttpUtils.postData(WeChatUtils.weChatPayUrl, WeChatUtils.mapToXml(map),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            resultMap = WeChatUtils.xmlToMap(resultXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")) {
            //成功之后保存自己的业务逻辑
            kCoursePurchase.setOutTradeNoWx(outTradeNoWx);
            int i=kCoursePurchaseService.updateKCoursePurchase(kCoursePurchase);
            if(i==0){
                map.put("code","error");
            }

            Map<String, String> dataMap = new HashMap<>();
            dataMap.put("appId", WeChatUtils.weChatAppid);
            dataMap.put("timeStamp", System.currentTimeMillis()/1000+"");
            dataMap.put("nonceStr", WeChatUtils.generateNonceStr());
            dataMap.put("package", "prepay_id=" + resultMap.get("prepay_id"));
            dataMap.put("signType", "MD5");

            try {
                dataMap.put("paySign", WeChatUtils.generateSignature(dataMap, WeChatUtils.weChatPayKey, "MD5"));
            } catch (Exception e) {
                e.printStackTrace();
            }

            return dataMap;
        }else {
            map.put("code","error");
            return map;
        }
    }


    @ResponseBody
    @ApiOperation(value = "回调")
    @RequestMapping("/app/weChatPayNotify")
    public String weChatPayNotify(HttpServletRequest request) {
        String resultStr = "";
        Map<String, String> returnMap = new HashMap<>();
        try {
            resultStr = new String(WeChatUtils.readInput(request.getInputStream()),"utf-8");
            System.out.println("支付回调："+resultStr);
            Map<String, String> resultMap = WeChatUtils.xmlToMap(resultStr);
            String resultCode = resultMap.get("result_code");
            String returnCode = resultMap.get("return_code");
            if("SUCCESS".equals(returnCode)&&"SUCCESS".equals(resultCode)) {
                Map<String, Object> map = new HashMap<>();
                map.put("out_trade_no =?", resultMap.get("out_trade_no"));
                /** 自己的业务逻辑 根据out_trade_no  查询订单信息**/
                KCoursePurchase kCoursePurchase =new KCoursePurchase();
                kCoursePurchase.setOutTradeNoWx(resultMap.get("out_trade_no"));
                System.out.println("查询到的订单编号");
                System.out.println(resultMap.get("out_trade_no"));
                List<KCoursePurchase> kCoursePurchaseList=kCoursePurchaseService.selectKCoursePurchaseList(kCoursePurchase);
                System.out.println("查询到的订单信息");
                System.out.println(kCoursePurchaseList.toString());
                if(kCoursePurchaseList.size()==0){
                    returnMap.put("return_code", "error");
                    returnMap.put("return_msg", "error");
                }
                KCoursePurchase kCoursePurchase1=kCoursePurchaseList.get(0);
                if(kCoursePurchase1.getState()==0){
                    //更新课程名额
                    KCourse kCourse =kCourseService.selectKCourseById(kCoursePurchaseList.get(0).getCourseId());
                    System.out.println("课程人数前"+kCourse.getSold());
                    kCourse.setSold(kCourse.getSold()+1);
                    System.out.println("课程人数后"+kCourse.getSold());
                    BigDecimal remaining = new BigDecimal(kCourse.getTotalQuota()).subtract(new BigDecimal(kCourse.getSold()));
                    kCourse.setRemainingQuota2(Integer.valueOf(String.valueOf(remaining)));
                    int i1=kCourseService.updateKCourse(kCourse);
                    System.out.println("更新课程人数");
                    System.out.println(i1);

                    //增加积分
                    this.inserKIntegralOrder(Long.valueOf(kCoursePurchaseList.get(0).getUserId()),kCourse.getExchangeIntegral(),"课程报名",4,kCoursePurchase1.getId());
                }
                kCoursePurchase1.setState(1);
                int i =kCoursePurchaseService.updateKCoursePurchase(kCoursePurchase1);
                System.out.println("更新订单状态");
                System.out.println(i);
                if(i==0){
                    returnMap.put("return_code", "error");
                    returnMap.put("return_msg", "error");
                }
                returnMap.put("return_code", "SUCCESS");
                returnMap.put("return_msg", "OK");
                return WeChatUtils.mapToXml(returnMap);
            }else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    public void inserKIntegralOrder(Long userId, Integer score, String name, int type, String activityId){

        //增加积分 先判断有无 有修改 无新增
        KIntegralOrder kIntegralOrder =new KIntegralOrder();
        kIntegralOrder.setUserId(String.valueOf(userId));
        List<KIntegralOrder> kIntegralOrderList=kIntegralOrderService.selectKIntegralOrderList(kIntegralOrder);
        if(kIntegralOrderList.size()>0){
            kIntegralOrder.setIntegral(kIntegralOrderList.get(0).getIntegral()+score);
            kIntegralOrder.setId(kIntegralOrderList.get(0).getId());
            kIntegralOrderService.updateKIntegralOrder(kIntegralOrder);
        }else {
            kIntegralOrder.setIntegral(score);
            kIntegralOrderService.insertKIntegralOrder(kIntegralOrder);
        }

        //增加记录
        KIntegralDetailed kIntegralDetailed =new KIntegralDetailed();
        kIntegralDetailed.setUserId(String.valueOf(userId));
        kIntegralDetailed.setIntegral(score);
        kIntegralDetailed.setType(String.valueOf(type));
        kIntegralDetailed.setIntegralSource(name);
        kIntegralDetailed.setActivityId(activityId);
        kIntegralDetailedService.insertKIntegralDetailed(kIntegralDetailed);
    }
}
